package com.wf.test_quartz_demo.service.impl;


import com.wf.test_quartz_demo.bean.CodeEnum;
import com.wf.test_quartz_demo.bean.CommonResult;
import com.wf.test_quartz_demo.bean.QuartzJobVO;
import com.wf.test_quartz_demo.bean.RecordsParam;
import com.wf.test_quartz_demo.mapper.QuartzJobInfoMapper;
import com.wf.test_quartz_demo.service.TestQuartzJobInfoService;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Description: 任务调度测试service
 */
@Slf4j
@Service
public class TestQuartzJobServiceImpl implements TestQuartzJobInfoService {
    @Resource
    private QuartzJobInfoMapper quartzJobMapper;
    @Resource
    private Scheduler scheduler;

    /**
     * 添加任务
     * @param param
     * @return
     */
    @Override
    public CommonResult<String> addJob(RecordsParam param) {
        try {
            if(param!=null){
                //动态控制job,根据job的类路径，创建JobDetail
                Class clsss = Class.forName(param.getClassPath());
                //设置job的业务逻辑类路径
                JobDetail jobDetail = JobBuilder.newJob(clsss)
                        //设置job的名称，组名称
                        .withIdentity(param.getJobName(), param.getJobGroupName())
                        //设置对job的说明描述
                        .withDescription(param.getRemarks())
                        //向job传递参数
                        .usingJobData(param.getJobDataMap())
                        .build();

                // 创建触发器
                CronTrigger trigger = TriggerBuilder.newTrigger()
                        //设置触发器的名称，触发器的组名
                        .withIdentity(param.getTriggerName(), param.getTriggerGroupName())
                        .startNow()
                        //设置corn表达式
                        .withSchedule(CronScheduleBuilder.cronSchedule(param.getCorn()))
                        .build();
                // 启动调度器
                scheduler.start();
                scheduler.scheduleJob(jobDetail, trigger);

                return CommonResult.success("添加任务成功");
            }

            return CommonResult.fail(CodeEnum.ILLEGAL_PARAMETER);

        } catch (Exception e) {
            log.info("创建定时任务失败{}" , e.getMessage());
            return CommonResult.fail("添加任务失败："+e.getMessage());
        }

    }


    /**
     * 暂停任务
     * @param param
     * @return
     */
    @Override
    public CommonResult<String> pauseJob(RecordsParam param)  {
        try {
            if(param!=null){
                //设置任务名称，任务组名称
                scheduler.pauseJob(JobKey.jobKey(param.getJobName(), param.getJobGroupName()));
                return CommonResult.success("暂停任务成功");
            }
            return CommonResult.fail(CodeEnum.ILLEGAL_PARAMETER);

        } catch (SchedulerException e) {
            log.info("暂停任务失败{}" , e.getMessage());
            return CommonResult.fail("暂停任务失败："+e.getMessage());
        }

    }

    /**
     * 恢复任务
     * @param param
     * @return
     */
    @Override
    public CommonResult<String> resumeJob(RecordsParam param) {
        try {
            if(param!=null){
                //设置任务名称，任务组名称
                scheduler.resumeJob(JobKey.jobKey(param.getJobName(), param.getJobGroupName()));
                return CommonResult.success("恢复任务成功");
            }
            return CommonResult.fail(CodeEnum.ILLEGAL_PARAMETER);

        } catch (SchedulerException e) {
            log.info("恢复任务失败{}" , e.getMessage());
            return CommonResult.fail("恢复任务失败："+e.getMessage());
        }

    }

    /**
     * 修改任务
     * @param param
     * @return
     */
    @Override
    @Transactional
    public CommonResult<String> updateJob(RecordsParam param) {
            if(param!=null){
                //删除之前的任务
                deleteJob(param);
                //创建新的任务
                addJob(param);
                return CommonResult.success("修改任务成功");
            }
            return CommonResult.fail(CodeEnum.ILLEGAL_PARAMETER);

    }

    /**
     * 删除任务
     * @param param
     * @return
     */
    @Override
    public CommonResult<String> deleteJob(RecordsParam param) {
        try {
            if(param!=null){
                //设置任务名称，任务组名称
                scheduler.pauseTrigger(TriggerKey.triggerKey(param.getTriggerName(), param.getTriggerGroupName()));
                scheduler.unscheduleJob(TriggerKey.triggerKey(param.getTriggerName(), param.getTriggerGroupName()));
                scheduler.deleteJob(JobKey.jobKey(param.getJobName(), param.getJobGroupName()));
                return CommonResult.success("删除任务成功");
            }
            return CommonResult.fail(CodeEnum.ILLEGAL_PARAMETER);

        } catch (SchedulerException e) {
            log.info("删除任务失败{}" , e.getMessage());
            return CommonResult.fail("删除任务失败："+e.getMessage());
        }
    }

    @Override
    public CommonResult<List<QuartzJobVO>> getJobAndTriggerDetails(RecordsParam param) {
        param.setPageIndex((param.getPage() - 1) * param.getSize());
        //查询任务列表
        return CommonResult.success(quartzJobMapper.getJobAndTriggerDetails(param));
    }


}

